package cn.stronglink.assetmanage.business.inspection.view.repairDetail;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inspection.model.RepairDetailModel;
import cn.stronglink.assetmanage.business.inspection.presenter.RepairDetailPresenter;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.RepailDetailDao;
import cn.stronglink.assetmanage.dao.RepairDao;
import cn.stronglink.assetmanage.dao.SearchAssetDao;
import cn.stronglink.assetmanage.entity.RepailDetail;
import cn.stronglink.assetmanage.entity.Repair;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;

/**
 * 维修详情
 * Created by zhengjinglan on 2018/6/15.
 */

public class RepairDetailFragment extends Fragment implements View.OnClickListener, IScanerListener {

    private SearchAsset searchAsset;
    private RepairDetailModel repairDetailModel;
    private RepairDetailView repairDetailView;
    private RepairDetailPresenter repairDetailPresenter;
    private TextView tv_repair_detail_date, tv_repair_detail_people, et_repair_detail_rfid, et_repair_detail_assis_sn;
    private TextView txt_title_right, txt_title_left, txt_main_title;
    private Repair repair;
    private RepailDetail repailDetail;
    private TimerInfraraedScaner scaner;
    private boolean isSn = false;
    private String orderId;
    private Button btn_repairDetail_save;    //保存按钮
    private Map<String, RepailDetail> repailDetailMap = new HashMap<>();    //巡检到的商品

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_maintenance_detail, container, false);
        try {
            initViewAndData(view);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return view;
    }

    private void initViewAndData(View view) {

        txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
        txt_title_left.setVisibility(View.VISIBLE);
        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setVisibility(View.GONE);
        txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
        txt_main_title.setText("维修登记详情");
        repailDetail = new RepailDetail();
        btn_repairDetail_save = view.findViewById(R.id.btn_repairDetail_save);
        tv_repair_detail_people = view.findViewById(R.id.tv_repair_detail_people);
        tv_repair_detail_people.setText(User.getInstance().getName());
        tv_repair_detail_date = view.findViewById(R.id.tv_repair_detail_date);
        et_repair_detail_rfid = view.findViewById(R.id.et_repair_detail_rfid);
        et_repair_detail_rfid.setOnClickListener(this);
        et_repair_detail_assis_sn = view.findViewById(R.id.et_repair_detail_assis_sn);
        et_repair_detail_assis_sn.setOnClickListener(this);
        //保存详情到数据库，并将状态改为已巡检
        btn_repairDetail_save.setOnClickListener(this);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        tv_repair_detail_date.setText(format.format(new Date()));
        repairDetailModel = new RepairDetailModel();
        repairDetailView = new RepairDetailView(this, view);
        repairDetailPresenter = new RepairDetailPresenter(repairDetailModel, repairDetailView);
        Bundle bundle = getArguments();
        if (bundle != null) {
            String sn = bundle.getString(Constants.REPAIR_DETAIL_NO);
            orderId = bundle.getString(Constants.REPAIR_REGISTER_ORDER);
            if (orderId == null || "".equals(orderId)) {
                return;
            }
            //根据sn查询数据SearchAsset
            searchAsset = DaoManager.getDaoSession(this.getActivity()).getSearchAssetDao().queryBuilder().
                    whereOr(SearchAssetDao.Properties.SerialNo.eq(sn), SearchAssetDao.Properties.RfidNo.eq(sn)).list().get(0);

            repailDetail = DaoManager.getDaoSession(this.getActivity()).getRepailDetailDao().queryBuilder().
                    whereOr(RepailDetailDao.Properties.SerialNo.eq(sn), RepailDetailDao.Properties.RfidNo.eq(sn)).unique();
            repair = DaoManager.getDaoSession(this.getActivity()).getRepairDao().queryBuilder().
                    where(RepairDao.Properties.Id_.eq(orderId)).unique();
            if (searchAsset != null) {
                saveSearchAssetToRepairDetail();
                //显示
                repairDetailView.showDetail(repailDetail);
            }
        } else {
            repairDetailView.showToast(getString(R.string.get_no_data));
        }

        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setOnClickListener(this);
        this.scaner = new TimerInfraraedScaner(this.getContext());
        this.scaner.setScanerListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.txt_right_title:

                break;
            case R.id.et_repair_detail_rfid:
                //扫描二维码
                isSn = false;
                if (scaner == null) {
                    scaner = new TimerInfraraedScaner(this.getContext());
                    scaner.setScanerListener(this);

                }
                scaner.playSingle();
                break;
            case R.id.et_repair_detail_assis_sn:
                isSn = true;
                if (scaner == null) {
                    scaner = new TimerInfraraedScaner(this.getContext());
                    scaner.setScanerListener(this);
                }
                scaner.playSingle();
                break;
            case R.id.btn_repairDetail_save:
                if (repailDetail != null) {
                    List<RepailDetail> repailDetailList = new ArrayList<>();
                    repailDetailList = DaoManager.getDaoSession(this.getActivity()).getRepailDetailDao().queryBuilder().
                            where(RepailDetailDao.Properties.RepairId_.eq(orderId)).list();

                    repair.setDetailList(repailDetailList);
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                    repailDetail.setStatus(Constants.STATUS_THREE);
                    repailDetail.setExecuteTime(format.format(new Date()));

                    //将巡检详情遍历到Map中，便于快速查找
                    for (int i = 0; i < repailDetailList.size(); i++) {
                        RepailDetail detail = repailDetailList.get(i);

                        repailDetailMap.put(detail.getSerialNo(), repailDetail);
                    }
                    if (repailDetailMap.containsKey(repailDetail.getSerialNo())) {
                        //将巡检详情遍历到Map中，便于快速查找
                        for (int i = 0; i < repailDetailList.size(); i++) {
                            if (repailDetail.getSerialNo().equals(repailDetailList.get(i).getSerialNo())) {
                                repailDetailList.remove(i);
                                break;
                            }
                        }
                    }
                    repailDetailList.add(repailDetail);
                    repairDetailModel.saveRepairDetailata(repair);
                    getActivity().onBackPressed();
                } else {
                    ToastUtil.toastShort("维修详情信息为空");
                }
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (scaner != null) {
            this.scaner.stop();
            this.scaner.destory();
        }

    }

    @Override
    public void onScaning(List<String> data) {
        String resultData = data.get(data.size() - 1);
        if (isSn) {
            et_repair_detail_assis_sn.setText(resultData);
        } else {
            et_repair_detail_rfid.setText(resultData);
        }
        Log.e("rfid扫描", "二维码" + resultData);
    }


    private void saveSearchAssetToRepairDetail() {
        if (repailDetail == null) {
            repailDetail = new RepailDetail();
            if (searchAsset.getAssetName() != null) {
                repailDetail.setAssetName(searchAsset.getAssetName());
            }
            if (searchAsset.getSerialNo() != null) {
                repailDetail.setSerialNo(searchAsset.getSerialNo());
            }
            if (searchAsset.getTypeName() != null) {
                repailDetail.setTypeName(searchAsset.getTypeName());
            }
            if (searchAsset.getRfidNo() != null) {
                repailDetail.setRfidNo(searchAsset.getRfidNo());
            }


        }

    }


}
